/**
 * Worker管理器
 * 处理Worker的创建、通信和销毁
 */

const logger = require('./logger').logger;

// Worker实例缓存
const workerInstances = {};

/**
 * 创建并获取Worker实例
 * @param {string} workerName - Worker名称，用于缓存管理
 * @param {string} workerPath - Worker文件路径
 * @returns {Object} Worker管理对象
 */
function getWorker(workerName, workerPath) {
  // 检查缓存中是否已有此worker
  if (workerInstances[workerName]) {
    return workerInstances[workerName];
  }
  
  try {
    // 检查是否支持Worker
    if (!wx.canIUse('createWorker')) {
      logger.warn('当前环境不支持Worker');
      return createFallbackWorker(workerName);
    }
    
    // 创建Worker实例
    const worker = wx.createWorker(workerPath);
    
    // 创建Worker管理对象
    const workerManager = {
      worker: worker,
      name: workerName,
      
      // 发送消息到Worker
      postMessage: function(message) {
        try {
          worker.postMessage(message);
          return Promise.resolve();
        } catch (e) {
          logger.error(`发送消息到Worker(${workerName})失败`, e);
          return Promise.reject(e);
        }
      },
      
      // 监听Worker的消息
      onMessage: function(callback) {
        try {
          worker.onMessage(callback);
        } catch (e) {
          logger.error(`监听Worker(${workerName})消息失败`, e);
        }
      },
      
      // 终止Worker
      terminate: function() {
        try {
          worker.terminate();
          delete workerInstances[workerName];
          logger.info(`Worker(${workerName})已终止`);
          return Promise.resolve();
        } catch (e) {
          logger.error(`终止Worker(${workerName})失败`, e);
          return Promise.reject(e);
        }
      }
    };
    
    // 缓存Worker管理对象
    workerInstances[workerName] = workerManager;
    logger.info(`Worker(${workerName})创建成功`);
    
    return workerManager;
  } catch (e) {
    logger.error(`创建Worker(${workerName})失败，将使用回退方案`, e);
    return createFallbackWorker(workerName);
  }
}

/**
 * 创建回退Worker
 * 当Worker不可用时使用主线程模拟
 */
function createFallbackWorker(workerName) {
  logger.info(`为${workerName}创建主线程回退方案`);
  
  // 创建回退管理对象
  const fallbackManager = {
    worker: null,
    name: `${workerName}_fallback`,
    callbacks: [],
    
    // 模拟发送消息，在主线程中处理
    postMessage: function(message) {
      logger.debug(`回退Worker(${workerName})收到消息`, message);
      
      // 使用setTimeout模拟异步处理
      setTimeout(() => {
        try {
          // 根据消息类型处理不同任务
          const { type, data } = message;
          
          let result = null;
          switch (type) {
            case 'compute_data':
              result = { processed: true, value: data.value * 2 };
              break;
            case 'filter_array':
              if (!Array.isArray(data.array)) {
                throw new Error('Input is not an array');
              }
              const filtered = data.array.filter(item => item > (data.threshold || 0));
              result = {
                original: data.array.length,
                filtered: filtered.length,
                result: filtered
              };
              break;
            case 'sort_complex':
              if (!Array.isArray(data.items)) {
                throw new Error('Items must be an array');
              }
              const sorted = [...data.items].sort((a, b) => {
                if (data.sortBy && typeof a === 'object' && typeof b === 'object') {
                  return a[data.sortBy] - b[data.sortBy];
                }
                return a - b;
              });
              result = {
                sorted: sorted,
                count: sorted.length
              };
              break;
            default:
              result = { error: 'Unknown operation type' };
          }
          
          // 触发回调
          this.callbacks.forEach(callback => {
            try {
              callback({
                type: `${type}_result`,
                result: result,
                success: true
              });
            } catch (e) {
              logger.error('调用回退Worker回调失败', e);
            }
          });
        } catch (e) {
          // 处理错误
          logger.error('回退Worker处理消息错误', e);
          this.callbacks.forEach(callback => {
            try {
              callback({
                type: 'error',
                error: e.message || String(e),
                success: false
              });
            } catch (e) {
              logger.error('调用回退Worker错误回调失败', e);
            }
          });
        }
      }, 0);
      
      return Promise.resolve();
    },
    
    // 监听消息回调
    onMessage: function(callback) {
      if (typeof callback === 'function') {
        this.callbacks.push(callback);
      }
    },
    
    // 终止回退Worker
    terminate: function() {
      logger.info(`回退Worker(${workerName})已终止`);
      this.callbacks = [];
      delete workerInstances[workerName];
      return Promise.resolve();
    }
  };
  
  // 缓存回退管理对象
  workerInstances[workerName] = fallbackManager;
  
  return fallbackManager;
}

/**
 * 终止并移除所有Worker
 */
function terminateAllWorkers() {
  const workerNames = Object.keys(workerInstances);
  
  if (workerNames.length === 0) {
    return Promise.resolve();
  }
  
  logger.info(`正在终止所有Worker(${workerNames.join(', ')})`);
  
  const promises = workerNames.map(name => {
    const worker = workerInstances[name];
    return worker.terminate();
  });
  
  return Promise.allSettled(promises)
    .then(() => {
      logger.info('所有Worker已终止');
    })
    .catch(error => {
      logger.error('终止Worker时发生错误', error);
    });
}

module.exports = {
  getWorker,
  terminateAllWorkers
}; 